package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.feign.math.IFeiMathFeignClient;
import com.xmy.cultivate.feign.physics_outside.IPhysicsFeignClient;
import com.xmy.cultivate.service.IStoreGoodsService;
import com.xmy.cultivate.service.IStoreGoodsTypeService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 物次库存 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-07-30
 */
@RestController
@RequestMapping("/api/storeGoods")
public class StoreGoodsController {

    @Autowired
    IStoreGoodsService iStoreGoodsService;

    @Autowired
    @Lazy
    IStoreGoodsTypeService iStoreGoodsTypeService;

    @Autowired
    IFeiMathFeignClient iFeiMathFeignClient;

    @Autowired
    IPhysicsFeignClient iPhysicsFeignClient;


    @Autowired
    IdWorker idWorker;

    @GetMapping("/getClassTypeList")
    public Result getClassTypeList(@RequestParam("yearPart") Integer yearPart,
                                   @RequestParam("quarterNum") Integer quarterNum,
                                   @RequestParam("schoolId") Long schoolId,
                                   @RequestParam("subjectsId") Long subjectsId,
                                   @RequestParam("yearClassId") Integer yearClassId,
                                   @RequestParam(value = "classTypeId",required = false) Long classTypeId,
                                   @RequestParam(value = "goodsTypeId",required = false,defaultValue = "2") Long goodsTypeId){
        IPage<OrderApply> iPage = new Page<>(1, 10000);
        iStoreGoodsService.getClassTypeList(iPage,yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId);
        return new Result(Code.OK,new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()),"");
    }

    @GetMapping("/getMaxLessonNum")
    public Result getMaxLessonNum(@RequestParam("yearPart") Integer yearPart,
                                  @RequestParam("quarterNum") Integer quarterNum,
                                  @RequestParam("schoolId") Long schoolId,
                                  @RequestParam("subjectsId") Long subjectsId,
                                  @RequestParam("yearClassId") Integer yearClassId,
                                  @RequestParam(value = "classTypeId",required = false) Long classTypeId,
                                  @RequestParam(value = "goodsTypeId",required = false,defaultValue = "2") Long goodsTypeId){
        Integer count = iStoreGoodsService.getMaxLessonNum(yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId);
        Map<String,Object> map = new HashMap<>();
        map.put("maxLessonNum",count);
        return new Result(Code.OK,map,"");
    }

    /**
     * 获取库存
     * @param pageNum
     * @param pageSize
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param yearClassId
     * @param classTypeId
     * @param goodsTypeId
     * @return
     */
    @GetMapping("/getStoreGoodsList")
    public Result getStoreGoodsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                    @RequestParam("yearPart") Integer yearPart,
                                    @RequestParam("quarterNum") Integer quarterNum,
                                    @RequestParam("schoolId") Long schoolId,
                                    @RequestParam("subjectsId") Long subjectsId,
                                    @RequestParam("yearClassId") Integer yearClassId,
                                    @RequestParam("lessonType") Integer lessonType,
                                    @RequestParam("classTypeId") Long classTypeId,
                                    @RequestParam(value = "goodsTypeId",required = false,defaultValue = "2") Long goodsTypeId
                                    ){
        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);
        List<StoreGoods> storeGoodsList =  iStoreGoodsService.getStoreGoodsList(yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId,lessonType);
        iStoreGoodsService.getClassTypeList(iPage,yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId);
        Integer count = iStoreGoodsService.getMaxLessonNum(yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId);
        Map<String ,Object> map = new HashMap<>();
        map.put("list",storeGoodsList);
        map.put("maxLessonNum",count);
        map.put("classTypeList",new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        return new Result(Code.OK, map,"");

    }

    @GetMapping("getStoreGoodsTest")
    public Result getStoreGoodsTest(@RequestParam("yearPart") Integer yearPart,
                                    @RequestParam("quarterNum") Integer quarterNum,
                                    @RequestParam("schoolId") Long schoolId,
                                    @RequestParam("subjectsId") Long subjectsId,
                                    @RequestParam("yearClassId") Integer yearClassId,
                                    @RequestParam("lessonType") Integer lessonType,
                                    @RequestParam("classTypeId") Long classTypeId,
                                    @RequestParam(value = "goodsTypeId",required = false,defaultValue = "2") Long goodsTypeId
    ){
        List<StoreGoods> storeGoodsList =  iStoreGoodsService.getStoreGoodsList(yearPart,quarterNum,schoolId,subjectsId,yearClassId,classTypeId,goodsTypeId,lessonType);
        List<Map<String,Object>> objList =this.queryCourseRecords(storeGoodsList);
        return new Result(Code.OK, objList,"");
    }


    public List<Map<String, Object>> queryCourseRecords(List<StoreGoods> storeGoodsList) {
        // 假设 courseRecords 是从数据库查询得到的原始数据
        List<Map<String, Object>> courseRecords = new ArrayList<>();

        // 2. 将 lesson 字段作为列名,成绩作为列值
        Map<Integer, Map<String, Object>> pivotedData = storeGoodsList.stream()
                .collect(Collectors.toMap(
                        record -> (int) record.getLessonNum(),
                        record -> {
                            Map<String, Object> rowData = new HashMap<>();
                            rowData.put("yearPart", record.getYearPart());
                            rowData.put("quarterNum", record.getQuarterNum());
                            rowData.put("class_type_id", record.getClassTypeId());
                            rowData.put("year_class_id", record.getYearClassId());
                            rowData.put("lesson_" + record.getLessonNum(), record.getGoodsCount());
                            return rowData;
                        },
                        (oldValue, newValue) -> {
                            oldValue.putAll(newValue);
                            return oldValue;
                        }
                ));

        // 3. 将结果转换为列表形式
        return new ArrayList<>(pivotedData.values());
    }

    /**
     * 入库
     * @param storeGoods
     * @return
     */
    @PostMapping("/addStoreGoods")
    @RepeatSubmit(expireSeconds = 30)
    public Result addStoreGoods(@RequestBody StoreGoods storeGoods){
        StoreGoodsType storeGoodsType = iStoreGoodsTypeService.getById(2L);
        storeGoods.setGoodsTypeId(storeGoodsType.getId());
        storeGoods.setName(storeGoodsType.getName());
        storeGoods.setType(1);
        storeGoods.setBatchNum(idWorker.nextId());
        iStoreGoodsService.addStoreGoods(storeGoods);
        return new Result(Code.OK, "","");
    }

    /**
     * 加订(确认)
     * @param storeGoods
     * @return
     */
    @PostMapping("/addDrawUpStoreGoods")
    @RepeatSubmit(expireSeconds = 10)
    public Result addDrawUpStoreGoods(@RequestBody StoreGoods storeGoods){
        StoreGoodsType storeGoodsType = iStoreGoodsTypeService.getById(2L);
        storeGoods.setGoodsTypeId(storeGoodsType.getId());
        storeGoods.setName(storeGoodsType.getName());
        storeGoods.setType(2);//加订为2
        storeGoods.setBatchNum(idWorker.nextId());//批次号
        iStoreGoodsService.addStoreGoods(storeGoods);
        return new Result(Code.OK, "","");
    }

    @PostMapping("/addDrawUpStoreGoodsBatch")
    @RepeatSubmit(expireSeconds = 5)
    public Result addDrawUpStoreGoodsBatch(@RequestBody StoreGoodsBatch storeGoodsBatch){
        iStoreGoodsService.addStoreGoodsBatch(storeGoodsBatch);
        return new Result(Code.OK, "","");
    }


    /**
     * 确认下单
     * @param storeGoods
     * @return
     */
    @PostMapping("/affirmAddOrder")
    @RepeatSubmit(expireSeconds = 5)
    public Result affirmAddOrder(@RequestBody StoreGoods storeGoods){
        iStoreGoodsService.affirmAddOrder(storeGoods);
        return new Result(Code.OK, "","");
    }

    /**
     * 选择未入库的下单信息确认入库
     * @return
     */
    @PostMapping("/affirmAddStoreGoods")
    @RepeatSubmit(expireSeconds = 5)
    public Result affirmAddStoreGoods(@RequestBody StoreGoods storeGoods){
        iStoreGoodsService.affirmAddStoreGoods(storeGoods);
        return new Result(Code.OK, "","");
    }


    /**
     * 需加订
     * @param pageNum
     * @param pageSize
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param lessonType
     * @param subjectsId
     * @param yearClassId
     * @param classTypeId
     * @param goodsTypeId
     * @return
     */
    @GetMapping("/getNeedOrder")
    public Result getNeedOrder(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                               @RequestParam("yearPart") Integer yearPart,
                               @RequestParam("quarterNum") Integer quarterNum,
                               @RequestParam("schoolId") Long schoolId,
                               @RequestParam("lessonType") Integer lessonType,
                               @RequestParam("subjectsId") Long subjectsId,
                               @RequestParam(value = "yearClassId",required = false) Integer yearClassId,
                               @RequestParam("classTypeId") Long classTypeId,
                               @RequestParam(value = "goodsTypeId",required = false,defaultValue = "2") Long goodsTypeId){

        Map<String,Object> map = null;
        lessonType = 1;//获取的是精品课所在班级数据
        if (subjectsId.equals(2L)){
            map = iFeiMathFeignClient.getNeedOrder(pageNum,pageSize,yearPart,quarterNum,schoolId,lessonType,subjectsId,yearClassId,classTypeId,goodsTypeId);
        }else {
            map = iPhysicsFeignClient.getNeedOrder(pageNum,pageSize,yearPart,quarterNum,schoolId,lessonType,subjectsId,yearClassId,classTypeId,goodsTypeId);
        }
        return new Result(Code.OK, map,"");
    }


}
